<template>
  <Dialog
    v-model="dialogVisible"
    width="80%"
    title="发货"
    max-height="80vh"
    :before-close="() => closeDialog(formRef)"
  >
    <div class="flex flex-items-center my-20px text-14px font-bold">{{ t('order.orderInfo') }}</div>
    <ElDescriptions border :column="2">
      <ElDescriptionsItem :label="t('common.serialNumber')">
        {{ currentRow?.id }}
      </ElDescriptionsItem>
      <ElDescriptionsItem :label="t('order.orderCode')">
        {{ currentRow?.order_no }}
      </ElDescriptionsItem>
      <ElDescriptionsItem
        :label="t('order.thisDeliveryOrderNumber')"
        v-if="currentRow?.current_serial_number"
      >
        {{ currentRow?.current_serial_number }}
      </ElDescriptionsItem>
      <ElDescriptionsItem :label="t('order.receiptMethod')">
        {{ useEnumeratePicker(operatorOptions.delivery_method, currentRow?.delivery_method ?? '') }}
      </ElDescriptionsItem>
      <ElDescriptionsItem :label="t('order.order_remark')">
        {{ currentRow?.order_remark }}
      </ElDescriptionsItem>
      <ElDescriptionsItem :label="t('order.notes')">
        {{ currentRow?.notes }}
      </ElDescriptionsItem>
    </ElDescriptions>

    <!-- 自提 -->
    <template v-if="currentRow?.delivery_method === 0">
      <div class="flex flex-items-center my-20px text-14px font-bold">{{
        t('dealerAssetManagement.selfPickupInformation')
      }}</div>
      <ElDescriptions border :column="2">
        <ElDescriptionsItem label="姓名">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_name }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="电话">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_phone }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="身份证">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_passport }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="车辆信息">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_vehicle }}
          </template>
        </ElDescriptionsItem>
      </ElDescriptions>
      <div v-if="currentRow.pickup[0].annex_list.length" class="flex py-20px">
        <div class="text-14px font-bold w-60px">附件:</div>
        <div class="flex flex-wrap gap-10px">
          <div v-for="item in currentRow.pickup[0].annex_list" :key="item.id" class="w-60px h-60px">
            <template v-if="isImage(item.url)">
              <el-image :src="item.url" :preview-src-list="[item.url]" class="w-full h-full" />
            </template>
            <template v-else>
              <a :href="item.url" target="_blank">{{ item.name }}</a>
            </template>
          </div>
        </div>
      </div>
    </template>

    <!-- 仓内过货 -->
    <template v-if="currentRow?.delivery_method === 2">
      <div class="flex flex-items-center my-20px text-14px font-bold">仓内过货信息</div>
      <ElDescriptions border :column="2">
        <ElDescriptionsItem label="姓名">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_name }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="电话">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_phone }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="护照">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].pickup_passport }}
          </template>
        </ElDescriptionsItem>
        <ElDescriptionsItem label="仓库code">
          <template v-if="currentRow?.pickup.length">
            {{ currentRow.pickup[0].warehouse_code }}
          </template>
        </ElDescriptionsItem>
      </ElDescriptions>
      <div v-if="currentRow.pickup[0].annex_list.length" class="flex py-20px pl-10px">
        <div class="text-14px font-bold w-60px">附件:</div>
        <div class="flex flex-wrap gap-10px">
          <div v-for="item in currentRow.pickup[0].annex_list" :key="item.id" class="w-60px h-60px">
            <template v-if="isImage(item.url)">
              <el-image :src="item.url" :preview-src-list="[item.url]" class="w-full h-full" />
            </template>
            <template v-else>
              <a :href="item.url" target="_blank">{{ item.name }}</a>
            </template>
          </div>
        </div>
      </div>
    </template>

    <!--    商品信息-->
    <div class="flex flex-items-center my-20px text-14px font-bold">{{
      t('order.deliveryGoods')
    }}</div>
    <el-table
      :data="shopTableList"
      highlight-current-row
      stripe
      border
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column
        :label="t('wholesalOrder.warehouse')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(warehouseList, row.wid) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('wholesalOrder.code')"
        prop="code"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.name')"
        prop="name"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.brand')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(brandList, row.brand) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('wholesalOrder.computingPower')"
        prop="hashrate"
        min-width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.warranty')"
        prop="expiration_date"
        min-width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.type')"
        min-width="120"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(warehouseTypeList, row.is_futures) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('wholesalOrder.arrivalDate')"
        prop="arrival_date"
        min-width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('order.theNumberOfShipments')"
        min-width="120"
        prop="ship_quantity"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <div>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-40px"></div>
      <!--    表单-->
      <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="86px">
        <div v-if="visible">
          <div class="w-full flex justify-between">
            <el-form-item :label="t('dealerAssetManagement.checkouts.firstName')" prop="first_name">
              <el-input
                v-model="form.first_name"
                :placeholder="t('dealerAssetManagement.checkouts.firstName')"
                clearable
              />
            </el-form-item>
            <el-form-item :label="t('dealerAssetManagement.checkouts.lastName')" prop="last_name">
              <el-input
                v-model="form.last_name"
                :placeholder="t('dealerAssetManagement.checkouts.lastName')"
                clearable
              />
            </el-form-item>
            <el-form-item :label="t('dealerAssetManagement.checkouts.zipCode')" prop="zip_code">
              <el-input
                v-model="form.zip_code"
                :placeholder="t('dealerAssetManagement.checkouts.zipCode')"
                clearable
              />
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item :label="t('dealerAssetManagement.checkouts.country')" prop="country_id">
              <el-select-v2
                v-model="form.country_id"
                :teleported="false"
                :placeholder="t('dealerAssetManagement.checkouts.country')"
                filterable
                allow-create
                :props="selectProps"
                :options="countryOptions"
                size="large"
                clearable
                @change="handleChangeCountry"
              />
            </el-form-item>
            <el-form-item
              :label="t('dealerAssetManagement.checkouts.state')"
              prop="state_id"
              v-if="stateOptions.length || form.state_id"
            >
              <el-select-v2
                v-model="form.state_id"
                :placeholder="t('dealerAssetManagement.checkouts.state')"
                filterable
                allow-create
                :props="selectProps"
                :options="stateOptions"
                size="large"
                clearable
                @change="handleChangeState"
              />
            </el-form-item>
            <el-form-item :label="t('dealerAssetManagement.checkouts.city')" prop="city_id">
              <el-select-v2
                v-model="form.city_id"
                :placeholder="t('dealerAssetManagement.checkouts.city')"
                filterable
                clearable
                allow-create
                :props="selectProps"
                :options="cityOptions"
                size="large"
              />
            </el-form-item>
            <el-form-item v-if="!stateOptions.length" />
          </div>
          <div class="flex">
            <el-form-item :label="t('dealerAssetManagement.checkouts.phone')" prop="phone">
              <el-input
                v-model="form.phone"
                :placeholder="t('dealerAssetManagement.checkouts.phone')"
                clearable
              />
            </el-form-item>
            <el-form-item :label="t('dealerAssetManagement.checkouts.email')" prop="email">
              <el-input
                v-model="form.email"
                :placeholder="t('dealerAssetManagement.checkouts.email')"
                clearable
              />
            </el-form-item>
            <el-form-item />
          </div>
          <el-form-item :label="t('dealerAssetManagement.checkouts.address')" prop="address">
            <el-input
              v-model="form.address"
              :placeholder="t('dealerAssetManagement.checkouts.address')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="t('dealerAssetManagement.alternateAddress')" prop="address2">
            <el-input
              v-model="form.address2"
              :placeholder="t('dealerAssetManagement.alternateAddress')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="t('dealerAssetManagement.company')" prop="company">
            <el-input
              v-model="form.company"
              :placeholder="t('dealerAssetManagement.company')"
              clearable
            />
          </el-form-item>
        </div>
        <div class="w-full flex justify-between">
          <div class="w-full mr-20px">
            <el-form-item :label="t('order.logisticsCompanies')" prop="logistics_company">
              <el-tree-select
                v-model="form.logistics_company"
                :data="logisticsCompanyTree"
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'id',
                  disabled: (data: any) => data.company_type === 1
                }"
                :placeholder="t('order.logisticsCompaniesMsg')"
                clearable
                :render-after-expand="false"
                :check-strictly="true"
                :default-expand-all="true"
              />
            </el-form-item>
            <el-form-item :label="t('order.logisticsVouchers')" prop="logistics_voucher">
              <UploadFilesBase
                ref="uploadRef"
                class="w-full"
                :directory="2"
                :limit="99"
                :fileListMap="form.logistics_voucher"
                @upload-success-res="handleUploadCallback"
              />
            </el-form-item>
          </div>
          <div class="w-full mr-20px">
            <el-form-item :label="t('order.trackingNumber')">
              <el-input v-model="form.logistics_no" :placeholder="t('order.trackingNumberMsg')" />
            </el-form-item>

            <el-form-item :label="t('order.cost')" prop="cost">
              <!-- <el-input v-model="form.cost" type="number" :placeholder="t('order.costMsg')" /> -->
              <div class="flex flex-col">
                <div
                  v-for="(item, index) in form.cost"
                  :key="item.type"
                  class="cost-row"
                  style="display: flex; align-items: center; margin-bottom: 8px"
                >
                  <el-select
                    v-model="item.type"
                    placeholder="请选择成本类型"
                    style="width: 140px; margin-right: 8px"
                  >
                    <el-option
                      v-for="option in operatorOptions.costing"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                      :disabled="form.cost.some((c, i) => c.type === option.value && i !== index)"
                    />
                  </el-select>
                  <el-input-number
                    v-model="item.amount"
                    :min="0"
                    :max="999999"
                    placeholder="金额"
                    style="width: 140px; margin-right: 8px"
                  />
                  <el-select
                    v-model="item.transaction_currency_id"
                    placeholder="币种"
                    style="width: 140px; margin-right: 8px"
                  >
                    <el-option
                      v-for="currencyItem in operatorOptions.currency"
                      :key="currencyItem.value"
                      :label="currencyItem.label"
                      :value="currencyItem.value"
                    />
                  </el-select>
                  <el-button type="danger" @click="removeCostRow(index)">删除</el-button>
                </div>
                <div class="flex items-center">
                  <el-button type="primary" @click="addCostRow">添加</el-button>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="w-full">
            <el-form-item :label="t('order.shippingTime')" prop="ship_date">
              <el-date-picker
                v-model="form.ship_date"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="t('common.selectText') + t('order.shippingTime')"
              />
            </el-form-item>
            <el-form-item :label="t('order.remark')">
              <el-input
                v-model="form.notes"
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 10 }"
                :placeholder="t('order.remarkMsg')"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('order.delivery') }} </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import UploadFile from '@/components/UploadFile/index.vue'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { useEnumeratePicker } from '@/utils'
import { deliveryDataApi, getOrderEnumApi, getAreaEnumApi, getCountryEnumApi } from '@/api/order'
import { createImageViewer } from '@/components/ImageViewer'
import { computed } from 'vue'

const emit = defineEmits(['refresh'])
const { t } = useI18n()
const { query } = useRoute()

const dialogVisible = ref<boolean>(false)
const shopTableList = ref<Array<Record<string, any>>>([])
const visible = ref<boolean>(false)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  first_name: '',
  last_name: '',
  zip_code: '',
  country_id: null,
  city_id: null,
  state_id: null,
  address: '',
  address2: '',
  company: '',
  phone: '',
  email: '',
  logistics_company: '',
  cost: [] as any[],
  transaction_currency_id: 214,
  logistics_voucher: [],
  logistics_no: '',
  ship_date: dayjs().format('YYYY-MM-DD'),
  notes: ''
})

const brandList = ref<Array<Record<string, any>>>([])
const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])
const logisticsCompanyList = ref<Array<Record<string, any>>>([])
const logisticsCompanyTree = ref<Array<Record<string, any>>>([])

const selectProps = ref({
  label: 'name',
  value: 'id'
})
const countryOptions = ref<any[]>([])
const cityOptions = ref<any[]>([])
const stateOptions = ref<any[]>([])
const cityOptionsCopy = ref<any[]>([])
const dropDownBoxQuery = async () => {
  const resp = await getCountryEnumApi()
  countryOptions.value = resp.data
}
//根据国家查询另外市和州的数据
const handleChangeCountry = async (val: string) => {
  form.value.state_id = null
  form.value.city_id = null
  // setTimeout(() => {
  //   formRef.value.clearValidate()
  // })
  const resp = await getAreaEnumApi({ country_id: val })

  if (!resp.data.state.length) {
    stateOptions.value = resp.data.state
    cityOptions.value = resp.data.city
    cityOptionsCopy.value = []
  } else {
    stateOptions.value = resp.data.state
    cityOptionsCopy.value = resp.data.city
    cityOptions.value = []
  }
}
//根据州/省的id过滤出市/区的数据
const handleChangeState = (val: string | number) => {
  return new Promise((resolve) => {
    form.value.city_id = null
    // setTimeout(() => {
    //   formRef.value.clearValidate()
    // })
    cityOptions.value = cityOptionsCopy.value.filter(
      (item: Record<string, any>) => item.state_id == val
    )
    resolve(true)
  })
}
const rules = ref<FormRules>({
  first_name: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.firstNameValidation'),
      trigger: 'change'
    }
  ],
  last_name: [
    {
      required: false,
      message: t('dealerAssetManagement.checkouts.lastNameValidation'),
      trigger: 'change'
    }
  ],
  zip_code: [
    {
      required: false,
      message: t('dealerAssetManagement.checkouts.zipCodeValidation'),
      trigger: 'change'
    }
  ],
  country_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.countryValidation'),
      trigger: 'change'
    }
  ],
  city_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.cityValidation'),
      trigger: 'change'
    }
  ],
  state_id: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.stateValidation'),
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.addressValidation'),
      trigger: 'change'
    }
  ],
  phone: [
    {
      required: true,
      message: t('dealerAssetManagement.checkouts.phoneValidation'),
      trigger: 'change'
    }
  ],
  email: [
    {
      required: false, // 取消必填，改为可选字段
      trigger: ['change', 'blur'],
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          // 只有填写了值才进行校验
          const reg =
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
          if (reg.test(value)) {
            callback() // 校验通过
          } else {
            callback(new Error(t('dealerAssetManagement.checkouts.emailValidationMsg'))) // 校验失败
          }
        } else {
          callback() // 未填写值，直接通过校验
        }
      }
    }
  ],
  logistics_company: [
    {
      required: true,
      message: t('order.logisticsCompaniesMsg'),
      trigger: 'change'
    }
  ],
  ship_date: [
    {
      required: true,
      message: t('common.selectText') + t('order.shippingTime'),
      trigger: 'change'
    }
  ]
  // cost: [
  //   {
  //     required: true,
  //     message: t('order.costMsg'),
  //     trigger: 'blur'
  //   }
  // ],
  // logistics_voucher: [
  //   {
  //     type: 'array',
  //     required: true,
  //     message: t('order.logisticsVoucherMsg'),
  //     trigger: 'change'
  //   }
  // ]
})

const handleRemoveFile = (val: any) => {
  if (form.value.logistics_voucher && form.value.logistics_voucher.length) {
    form.value.logistics_voucher = form.value.logistics_voucher.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.logistics_voucher.push(...val)
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}
const uploadRef = ref<any>(null)
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    const resp = await deliveryDataApi({
      order_id: JSON.parse(decodeURIComponent(query.data as string))?.id || '',
      list: shopTableList.value,
      shop_fl_warehouse: shop_fl_warehouse.value
    })
    if (resp.code === 0) {
      ElMessage.success(t('order.deliveryMsg'))
      closeDialog(formEl)
      emit('refresh')
    }
    return
  }
  await formEl.validate(async (valid) => {
    if (valid) {
      // const params = JSON.parse(JSON.stringify(form.value))
      // 校验成本数组
      if (Array.isArray(form.value.cost)) {
        for (let i = 0; i < form.value.cost.length; i++) {
          const item = form.value.cost[i]
          if (!item.type || item.amount === '' || item.amount === null || item.amount === 0) {
            ElMessage.warning('成本类型、金额不能为空')
            return
          }
        }
      }

      let result = await uploadRef.value?.uploadImg()
      console.log('result', result)
      if (result) {
        ElMessage.warning('上传中,请稍等')
        return
      }

      let country_id_v = null
      let country_name_v = null
      if (form.value.country_id) {
        let obj = countryOptions.value.find((item: any) => item.id == form.value.country_id)
        if (obj) {
          country_id_v = obj.id
          country_name_v = obj.name
        } else {
          country_name_v = form.value.country_id
          country_id_v = null
        }
      }
      let state_id_v = null
      let state_name_v = null
      if (form.value.state_id) {
        let obj = stateOptions.value.find((item: any) => item.id == form.value.state_id)
        if (obj) {
          state_id_v = obj.id
          state_name_v = obj.name
        } else {
          state_name_v = form.value.state_id
          state_id_v = null
        }
      }
      let city_id_v = null
      let city_name_v = null
      if (form.value.city_id) {
        // params.city_name = null
        let obj = cityOptions.value.find((item: any) => item.id == form.value.city_id)
        if (obj) {
          city_id_v = obj.id
          city_name_v = obj.name
        } else {
          city_name_v = form.value.city_id
          city_id_v = null
        }
      }
      const params = JSON.parse(
        JSON.stringify(
          Object.assign(
            {},
            {
              logistics_company: form.value.logistics_company,
              cost: form.value.cost,
              logistics_voucher: form.value.logistics_voucher,
              logistics_no: form.value.logistics_no,
              notes: form.value.notes,
              ship_date: form.value.ship_date,
              shippinAddress: {
                first_name: form.value.first_name,
                last_name: form.value.last_name,
                zip_code: form.value.zip_code,
                country_id: country_id_v,
                country_name: country_name_v,
                city_id: city_id_v,
                city_name: city_name_v,
                state: state_name_v,
                state_id: state_id_v,
                address: form.value.address,
                address2: form.value.address2,
                company: form.value.company,
                phone: form.value.phone,
                email: form.value.email
              }
            }
          )
        )
      )
      params.wid = shopTableList.value[0].wid
      params.logistics_voucher = params.logistics_voucher.map(
        (item: Record<string, any>) => item.id
      )
      params.order_id = (query.id as string) || ''
      params.list = shopTableList.value
      params.shop_fl_warehouse = shop_fl_warehouse.value
      params.is_part_delivery = query.is_part_delivery == 'true' ? true : false
      console.log('params', params)
      const resp = await deliveryDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('order.deliveryMsg'))
        closeDialog(formEl)
        emit('refresh')
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  form.value = {
    first_name: '',
    last_name: '',
    zip_code: '',
    country_id: null,
    city_id: null,
    state_id: null,
    address: '',
    address2: '',
    company: '',
    phone: '',
    email: '',
    logistics_company: '',
    cost: [] as any[],
    transaction_currency_id: 214,
    logistics_voucher: [],
    logistics_no: '',
    notes: ''
  }
  if (formEl) formEl.resetFields()
  dialogVisible.value = false
}
const shop_fl_warehouse = ref(0)
const operatorOptions = ref<Record<string, any>>({})
const currentRow = ref<any>({})
const getDropDownBoxInfo = async (
  checkedList: Array<Record<string, any>>,
  row: Record<string, any>
) => {
  try {
    console.log('row', row)
    currentRow.value = row
    dialogVisible.value = false
    shopTableList.value = checkedList
    visible.value = row.delivery_method === 1
    shop_fl_warehouse.value = row.shop_fl_warehouse ? 1 : 0
    const resp = await getOrderEnumApi({ field: 'all' })
    operatorOptions.value = resp.data
    brandList.value = resp.data.brand
    warehouseList.value = resp.data.warehouse
    warehouseTypeList.value = resp.data.is_futures
    logisticsCompanyList.value = resp.data.logistics_company
    logisticsCompanyTree.value = resp.data.logistics_company_tree || resp.data.logistics_company
    if (row.delivery && row.delivery.length && row.delivery_method === 1) {
      await handleChangeCountry(row.delivery[0].country_id)
      if (row.delivery[0].state_id) {
        cityOptions.value = cityOptionsCopy.value.filter(
          (item: Record<string, any>) => item.state_id == row.delivery[0].state_id
        )
      }
      form.value = Object.assign({}, form.value, {
        first_name: row.delivery[0].first_name,
        last_name: row.delivery[0].last_name,
        zip_code: row.delivery[0].zip_code,
        country_id: row.delivery[0].country_id || row.delivery[0].country_name,
        country_name: row.delivery[0].country_name,
        city_id:
          cityOptions.value.find((item: any) => item.id == row.delivery[0].city_id)?.id ||
          row.delivery[0].city_name,
        city_name: row.delivery[0].city_name,
        state: row.delivery[0].state,
        state_id:
          stateOptions.value.find((item: any) => item.id == row.delivery[0].state_id)?.id ||
          row.delivery[0].state,
        address: row.delivery[0].address,
        address2: row.delivery[0].address2,
        company: row.delivery[0].company,
        phone: row.delivery[0].phone,
        email: row.delivery[0].email,
        ship_date: dayjs().format('YYYY-MM-DD')
      })
    }
    dialogVisible.value = true
  } catch (error) {}
}

const removeCostRow = (index: number) => {
  ElMessageBox.confirm('确定要删除该成本项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      form.value.cost.splice(index, 1)
    })
    .catch(() => {
      // 用户取消，无操作
    })
}
const addCostRow = () => {
  form.value.cost.push({ type: '', amount: '', transaction_currency_id: 214 })
}
const isImage = (url: string) => {
  if (!url) return false
  const imgExtensions = /\.(jpg|jpeg|png|gif|bmp|webp|svg|tiff)$/i // 图片扩展名正则（不区分大小写）
  // 提取 URL 中"?"之前的部分（排除参数），再匹配扩展名
  const urlWithoutParams = url.split('?')[0]
  return imgExtensions.test(urlWithoutParams)
}
onMounted(() => {
  dropDownBoxQuery()
})
defineExpose({
  dialogVisible,
  getDropDownBoxInfo
})
</script>
<style lang="less" scoped>
:deep(.el-form-item) {
  width: 100%;
  margin-right: 20px;
}

:deep(.el-input) {
  width: 100%;
  height: 40px !important;
}

.flex .el-form-item:last-child {
  margin-right: 0;
}

:deep(.el-input__inner) {
  height: 40px !important;
}

:deep(.el-select__wrapper) {
  height: 40px !important;
}

:deep(.el-form-item__label) {
  height: 40px !important;
  line-height: 40px !important;
}
</style>
